<template>
  <div>
    <div v-if="orderData" v-loading="loading">
      <el-button
        v-if="orderData.orderTypeCode == 'CompetitionOrder' || orderData.orderTypeCode == 'TrainingOrder' || orderData.orderTypeCode == 'LogisticsOrder'"
        :loading="downloadLoading"
        style="float: right;margin-top:15px;margin-right:20px"
        type="primary"
        size="mini"
        @click="downloadPdf()"
      >下载订单详情</el-button>
      <!-- <el-button
        v-if="orderData.orderStatusCode === 'TRADE_FINISHED'"
        style="float: right;margin-top:15px;margin-right:20px"
        type="primary"
        size="mini"
        @click="refund()"
      >退款</el-button> -->
      <div class="detail">
        <!-- 订单基本信息 -->
        <Info :order-data="orderData" :offline-data="offlineData" :detail="detail" :total-amount="TotalAmount" :pay-amount="PayAmount" :is-show-creator="isShowCreator" />
        <!-- 赛事订单 -->
        <div v-if="orderData.orderTypeCode == 'CompetitionOrder'">
          <CompetitionOrder :detail="detail" />
        </div>
        <!-- 后勤订单 -->
        <div v-if="orderData.orderTypeCode == 'LogisticsOrder'">
          <LogisticsOrder :detail="detail" />
        </div>
        <!-- 培训订单 -->
        <div v-if="orderData.orderTypeCode == 'TrainingOrder'">
          <TrainingOrder :detail="detail" />
        </div>
        <!-- 商城订单 -->
        <div v-if="orderData.orderTypeCode == 'MallOrder'">
          <MallOrder :detail="detail" :pay-amount="PayAmount" />
        </div>
        <!-- 会籍订单 -->
        <div v-if="orderData.orderTypeCode == 'ClubStudentMembershipCardOrder'" class="gl_mr_15">
          <ClubCardOrder :detail="detail" :pay-amount="PayAmount" />
        </div>
        <!-- 系统订单 -->
        <div v-if="orderData.orderTypeCode == 'SystemOrder'" class="gl_mr_15">
          <SystemOrder :detail="detail" :pay-amount="PayAmount" />
        </div>
        <!-- 保险订单 -->
        <div v-if="orderData.orderTypeCode == 'InsuranceOrder'" class="gl_mr_15">
          <InsuranceOrder :detail="detail" />
        </div>
      </div>

      <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
        <input ref="pay_params" type="text" name="pay_params" value="">
        <button type="submit">提交</button>
      </form>

      <div v-if="orderData.orderStatusCode == 'WAIT_BUYER_PAY'" class="gl_padding_15">
        <el-row type="flex" justify="end" align="right">
          <el-button size="mini" @click="cancelOrder(orderData.orderNo)">取消订单</el-button>
          <el-button v-if="orderData.isOnlinePayment" type="primary" size="mini" @click="payment(orderData.orderNo)">去支付</el-button>
        </el-row>
      </div>
    </div>
    <div v-else class="gl_noData">
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import Info from '@/components/Order/info';
import CompetitionOrder from '@/components/Order/competitionOrder';
import LogisticsOrder from '@/components/Order/logisticsOrder';
import TrainingOrder from '@/components/Order/trainingOrder';
import MallOrder from '@/components/Order/mallOrder';
import ClubCardOrder from '@/components/Order/clubCardOrder';
import SystemOrder from '@/components/Order/systemOrder';
import InsuranceOrder from '@/components/Order/insuranceOrder';
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import {
  api_GET_TradeOrderDetails, // 获取订单详情
  api_PUT_TradeCancellationOfOrder, // 取消订单
  api_GET_TradePayOrderParameter // 去支付
} from '@/extend/api/swaggerApi/app.js';
import {
  Api_GET_TradeOrderDetailsQO,
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';
export default {
  name: 'Detail',
  components: {
    Info,
    CompetitionOrder,
    LogisticsOrder,
    TrainingOrder,
    MallOrder,
    ClubCardOrder,
    SystemOrder,
    InsuranceOrder
  },
  data() {
    return {
      loading: false,
      downloadLoading: false,
      Api_GET_TradeOrderDetailsQO: new Api_GET_TradeOrderDetailsQO(),
      Api_GET_TradePayOrderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      pdfName: '订单详情',
      isShowCreator: false,
      orderData: {}, // 订单详细
      detail: {},
      offlineData: {
        busCollectionCodeList: []
      },
      TotalAmount: 0,
      PayAmount: 0,
      action: 'https://unipay.ydfuture.com/api/v1/trade/cashDesk' // 支付地址
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      user: state => state.user.info.currentOrganizationUnit.typeCode
    })
  },
  created() {
    this.getDict();
    this.getDetail();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    downloadPdf() {
      var that = this;
      this.downloadLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = this.orderData.name + '订单详情' + '.xlsx';
      let ReportName = '';
      if (this.orderData.orderTypeCode === 'CompetitionOrder' || this.orderData.orderTypeCode === 'LogisticsOrder') {
        ReportName = this.orderData.orderTypeCode === 'CompetitionOrder' ? 'CompetitionOrderDetailsExcel' : 'LogisticOrderDetailsExcel';
        api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: ReportName, OrderNo: this.Api_GET_TradeOrderDetailsQO.OrderNo }).then(res => {
          that.downloadLoading = false;
        }).catch(error => {
          that.downloadLoading = false;
          errorText(error).then(function(text) {
            that.$message({ type: 'error', message: text });
          });
        });
      } else if (this.orderData.orderTypeCode === 'TrainingOrder') {
        ReportName = 'TrainningOrderDetail';
        api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: ReportName, OrderNo: this.Api_GET_TradeOrderDetailsQO.OrderNo }, WEB_CONFIG.VUE_APP_SWAGGER_TRAIN_BASE).then(res => {
          that.downloadLoading = false;
        }).catch(error => {
          that.downloadLoading = false;
          errorText(error).then(function(text) {
            that.$message({ type: 'error', message: text });
          });
        });
      }
    },
    // 获取订单详情
    getDetail() {
      var that = this;
      this.loading = true;
      if (this.$route.query.out_trade_no) {
        this.Api_GET_TradeOrderDetailsQO.OrderNo = this.$route.query.out_trade_no;
      } else {
        this.Api_GET_TradeOrderDetailsQO.OrderNo = this.$route.query.id;
      }
      api_GET_TradeOrderDetails(this.Api_GET_TradeOrderDetailsQO).then(res => {
        that.orderData = res;
        that.offlineData.busCollectionCodeList = res.busCollectionCodeList || [];
        if (res.details) {
          that.detail = JSON.parse(res.details);
          console.log(that.detail);
        }
        that.TotalAmount = that.orderData.totalPrice;
        that.PayAmount = that.orderData.payPrice;
        that.loading = false;
      }).catch(() => {
        that.loading = false;
      });
    },
    // 去支付
    payment(id) {
      var that = this;
      if (id) {
        // var href = parent.location.href;
        // var url = href.split('?');
        // var returnUrl = url[0].substring(0, url[0].length - 7);
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        that.Api_GET_TradePayOrderParameterQO.OrderNo = id;
        that.Api_GET_TradePayOrderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(that.Api_GET_TradePayOrderParameterQO).then(res => {
          this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
          this.$refs.form.submit();
        }).catch(() => {});
      }
    },
    // 取消订单
    cancelOrder(id) {
      var that = this;
      this.$confirm('您确定要取消订单吗?', '取消订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { orderNo: id };
        api_PUT_TradeCancellationOfOrder(data)
          .then(res => {
            that.$message({
              type: 'success',
              message: '取消成功!'
            });
            that.getDetail();
          }).catch((error) => {
            that.$message({ type: 'error', message: error.error.message || '操作失败' });
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '放弃取消'
        });
      });
    },
    // 图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 退款
    refund() {
      var that = this;
      this.$confirm('您确定要退款吗?', '退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { orderNo: id };
        api_PUT_TradeCancellationOfOrder(data)
          .then(res => {
            that.$message({
              type: 'success',
              message: '退款成功!'
            });
            that.getDetail();
          }).catch((error) => {
            that.$message({ type: 'error', message: error.error.message || '操作失败' });
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '放弃退款'
        });
      });
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 是否被忽略
    isIgnore (tableProp, chargeCode) {
      const _map = this.ignoreMap;
      return !(chargeCode in _map[tableProp]);
    }
  }
};
</script>

<style scoped>
.detail {
  padding: 15px;
}
</style>
